package com.xq.shop.controller.user;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xq.shop.po.CartGood;
import com.xq.shop.po.Order;
import com.xq.shop.po.Product;
import com.xq.shop.po.User;
import com.xq.shop.service.user.IBaseService;
import com.xq.shop.service.user.ICartGoodService;
import com.xq.shop.service.user.IOrderService;
import com.xq.shop.service.user.IProductService;
import com.xq.shop.util.Const;
import com.xq.shop.util.GsonUtil;
import com.xq.shop.util.RespUtil;
import com.xq.shop.util.UserServiceFactory;
import com.xq.shop.vo.RespMsg;
import com.xq.shop.vo.SearchObject;
import com.xq.shop.vo.SearchValue;
import com.xq.shop.vo.RespMsg.Result;

@Controller
@RequestMapping("/user/")
public class CartGoodCtrl extends BaseCtrl<CartGood>{

	private ICartGoodService cartGoodService = UserServiceFactory.getCartGoodService();
	private IProductService productService = UserServiceFactory.getProductService();
	private IOrderService orderService = UserServiceFactory.getOrderService();
	
	@Override
	public IBaseService<CartGood> getService() {
		return cartGoodService;
	}

	@RequestMapping("cartGood_list.do")
	@ResponseBody
	public String list(SearchObject search, HttpServletRequest request){
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Const.User_Session);
		
		if(user != null){
			SearchValue value = new SearchValue();
			value.setName("user_id");
			value.setValue(user.getId());
			search.getCondition().add(value);
			return super.list(search, request);
		} else {
			return "";
		}
	}
	
	@RequestMapping("cartGood_delete.do")
	public void delete(String id, HttpServletRequest request, HttpServletResponse response){
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Const.User_Session);
		if(user == null){ return;}
			
		try {
			cartGoodService.delete(Long.valueOf(id), user.getId());
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("cartGood_save.do")
	public void save(CartGood cartGood, HttpServletRequest request, HttpServletResponse response){
		
		RespMsg msg = new RespMsg();	//设置返回信息
		
		if(cartGood.getProduct_id() == null){
			msg = new RespMsg(Result.error, "添加失败，商品不存在");
			RespUtil.renderJson(GsonUtil.toJson(msg), response);
			return;
		} else {
			Product product = productService.get(cartGood.getProduct_id());
			if(product == null){
				msg = new RespMsg(Result.error, "添加失败，商品不存在");
				RespUtil.renderJson(GsonUtil.toJson(msg), response);
				return;
			}
		}
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Const.User_Session);
		if(user != null){
			
			CartGood instance = cartGoodService.get(user.getId(), cartGood.getProduct_id());
			if(instance != null){
				cartGood.setCount(instance.getCount() + cartGood.getCount());
				cartGood.setId(instance.getId());
			}
			cartGood.setUser_id(user.getId());
			cartGoodService.saveOrUpdate(cartGood);
		}
		msg = new RespMsg(Result.success, "添加成功");
		RespUtil.renderJson(GsonUtil.toJson(msg), response);
	}
	
	@RequestMapping("cartGood_buyAgain.do")
	public ModelAndView buyAgain(Long orderId, HttpServletRequest request){
		
		Order order = orderService.get(orderId);
		if(order == null || order.getItems() == null || order.getItems().size() < 1){
			return null;
		}
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Const.User_Session);
		
		CartGood cartGood, instance;
		Product product;
		List<CartGood> list = new ArrayList<CartGood>();
		
		for(int i=0, len=order.getItems().size(); i<len; i++){
			
			if(order.getItems().get(i) == null || 
					order.getItems().get(i).getProduct() == null) continue;
			
			product = order.getItems().get(i).getProduct();
			cartGood = new CartGood();
			cartGood.setProduct_id(product.getId());
			cartGood.setUser_id(user.getId());
			cartGood.setCount(order.getItems().get(i).getQuantity());
			
			instance = cartGoodService.get(user.getId(), cartGood.getProduct_id());
			if(instance != null){
				cartGood.setCount(instance.getCount() + cartGood.getCount());
				cartGood.setId(instance.getId());
			}
			
			list.add(cartGood);
		}
		
		cartGoodService.saveOrUpdate(list);
		
		return new ModelAndView("order/cart");
	}
	
	@RequestMapping("cartGood_update.do")
	public void update(CartGood cartGood, HttpServletRequest request, HttpServletResponse response){
		
		RespMsg msg = new RespMsg();	//设置返回信息
		
		if(cartGood.getId() == null){
			msg = new RespMsg(Result.error, "修改失败，商品不存在");
			RespUtil.renderJson(GsonUtil.toJson(msg), response);
			return;
		}
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Const.User_Session);
		if(user != null){
			
			CartGood instance = cartGoodService.get(cartGood.getId());
			if(instance == null){
				msg = new RespMsg(Result.error, "修改失败，商品不存在");
			} else if(instance.getUser_id() != user.getId()){
				msg = new RespMsg(Result.error, "修改失败，无法修改其它用户数据");
			} else {
				cartGood.setUser_id(user.getId());
				cartGood.setProduct_id(instance.getProduct_id());
				cartGoodService.update(cartGood);
				msg = new RespMsg(Result.success, "添加成功");
			}
		}
		RespUtil.renderJson(GsonUtil.toJson(msg), response);
	}
}